package com.bidevalution.controller.api;

import com.qtp.core.model.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 在线预览pdf
 * @Auothor shenhui
 * @Date 2016/12/18 0018
 */
@Log4j2
@RestController
@RequestMapping("/displayPDF")
@Api(tags = "在线预览pdf")
public class DisplayPDFController extends BaseController{

    @Value("${download.file.path}")
    private String downloadFileUrl;

    @GetMapping("/displayPDF")
    @ApiOperation(value = "预览pdf", notes = "预览pdf")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "fileId", value = "文件id", required = true)
    })
    public void displayPDF(String fileId, HttpServletResponse response) {
        InputStream in = null;
        OutputStream out = null;
        PostMethod method = null;
        HttpClient client = new HttpClient();
        try {
            if (StringUtils.isEmpty(fileId)) {
                throw new Exception("文件id不能为空");
            }
            // /UploadedFile/958ED576-A1EB-4DB3-B8E1-340705B9D282/BFFBEB8C34957959DAC396C07387C71C
            String downloadUrl = downloadFileUrl + "/UploadedFile/" + fileId;
            //建立连接
            method = new PostMethod(downloadUrl);
            //执行url请求
            int result = client.executeMethod(method);
            if (result != 200) {
                throw new Exception("文件下载失败");
            }
            //获取文件
            in = method.getResponseBodyAsStream();
            out = new BufferedOutputStream(response.getOutputStream());
            //创建存放文件内容的数组
            byte[] buff =new byte[1024];
            //所读取的内容使用n来接收
            int n;
            //当没有读取完时,继续读取,循环
            while((n=in.read(buff))!=-1){
                //将字节数组的数据全部写入到输出流中
                out.write(buff,0,n);
            }
            //强制将缓存区的数据进行输出
            out.flush();
        } catch(Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if(method != null){
                    method.releaseConnection();
                }
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @RequestMapping(value = "/onlineShow", method = RequestMethod.GET)
    @ApiOperation(value = "pdf在线显示", notes = "pdf在线显示")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "fileId", value = "文件id", required = true)
    })
    public void onlineShow(HttpServletResponse response, @RequestParam("fileId") String fileId) {
        String downloadUrl = downloadFileUrl + "/UploadedFile/" + fileId;
        InputStream is = null;
        PostMethod method = null;
        HttpClient client = new HttpClient();
        OutputStream os = null;
        try {
            if (StringUtils.isBlank(fileId)){
                throw new Exception("文件id不可以为空！");
            }
            //建立连接
            method = new PostMethod(downloadUrl);
            //执行url请求
            int result = client.executeMethod(method);
            if (result != 200) {
                throw new Exception("文件下载失败");
            }
            //获取文件
            is = method.getResponseBodyAsStream();
            os = response.getOutputStream();

            response.setContentType("application/pdf");
            response.addHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-disposition", "inline;filename=" + fileId);
            response.addHeader("Connection", "close");
            IOUtils.write(IOUtils.toByteArray(is), os);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (method != null) {
                    method.releaseConnection();
                }
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @RequestMapping(value = "/onlineShowPdf", method = RequestMethod.GET)
    @ApiOperation(value = "pdf在线显示", notes = "pdf在线显示")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "fileId", value = "文件id", required = true)
    })
    public Response<String> onlineShowPdf(HttpServletResponse response, @RequestParam("fileId") String fileId) {
        return Response.ok(String.format("%s/UploadedFile/%s?preview=1", downloadFileUrl, fileId));
    }
}